package com.neusoft.EYSystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neusoft.EYSystem.dao.LevelProjectLinkDAO;
import com.neusoft.EYSystem.dao.NursingLevelDAO;
import com.neusoft.EYSystem.dao.NursingProjectDAO;
import com.neusoft.EYSystem.po.LevelProjectLink;
import com.neusoft.EYSystem.po.NursingLevel;
import com.neusoft.EYSystem.po.NursingProject;
import com.neusoft.EYSystem.po.PageResponseBean;
import com.neusoft.EYSystem.service.LevelProjectLinkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class LevelProjectLinkServiceImpl implements LevelProjectLinkService {

    // ✅ 工具方法：判断是否为合法字符串（排除 null、空串、"null"）
    private boolean isValid(String value) {
        return value != null && !value.trim().isEmpty() && !"null".equalsIgnoreCase(value.trim());
    }

    @Autowired
    private LevelProjectLinkDAO levelProjectLinkDAO;

    @Autowired
    private NursingLevelDAO nursingLevelDAO;

    @Autowired
    private NursingProjectDAO nursingProjectDAO;

    @Override
    public PageResponseBean<List<NursingProject>> getIncludedProjects(Long cur, Long number, NursingLevel nursingLevel, NursingProject nursingProject) {
        PageResponseBean<List<NursingProject>> response;

        try {
            // 0. 查询 level_project_link 表中当前级别的所有 projectId
            QueryWrapper<LevelProjectLink> linkWrapper = new QueryWrapper<>();
            linkWrapper.eq("level_id", nursingLevel.getLevelId());
            List<LevelProjectLink> links = levelProjectLinkDAO.selectList(linkWrapper);

            if (links.isEmpty()) {
                return new PageResponseBean<>(List.of()); // 当前级别没有任何关联项目，返回空列表
            }

            // 1. 提取所有 projectId
            List<Integer> projectIds = links.stream().map(LevelProjectLink::getProjectId).toList();

            // 2. 分页查询 nursing_project 表
            IPage<NursingProject> page = new Page<>(cur, number);
            QueryWrapper<NursingProject> projectWrapper = new QueryWrapper<>();
            projectWrapper.in("project_id", projectIds);

            // 3. 拼接模糊查询条件（项目名、状态）
            if (isValid(nursingProject.getName())) {
                projectWrapper.like("name", nursingProject.getName());
            }
            if (isValid(nursingProject.getStatus())) {
                projectWrapper.like("status", nursingProject.getStatus());
            }

            IPage<NursingProject> result = nursingProjectDAO.selectPage(page, projectWrapper);

            // 4. 封装结果
            List<NursingProject> list = result.getRecords();
            long total = result.getTotal();
            response = new PageResponseBean<>(list);
            response.setTotal(total);
        } catch (Exception e) {
            e.printStackTrace();
            response = new PageResponseBean<>(500, "查询护理级别已包含护理项目失败");
        }

        return response;
    }

    @Override
    public PageResponseBean<List<NursingProject>> getExcludedProjects(Long cur, Long number, NursingLevel nursingLevel, NursingProject nursingProject) {
        PageResponseBean<List<NursingProject>> response;

        try {
            // 0. 查询已包含的 projectId
            QueryWrapper<LevelProjectLink> linkWrapper = new QueryWrapper<>();
            linkWrapper.eq("level_id", nursingLevel.getLevelId());
            List<LevelProjectLink> links = levelProjectLinkDAO.selectList(linkWrapper);

            List<Integer> includedProjectIds = links.stream().map(LevelProjectLink::getProjectId).toList();

            // 1. 构造分页对象与查询条件
            IPage<NursingProject> page = new Page<>(cur, number);
            QueryWrapper<NursingProject> projectWrapper = new QueryWrapper<>();

            // 2. 条件排除：不在已包含 projectId 中
            if (!includedProjectIds.isEmpty()) {
                projectWrapper.notIn("project_id", includedProjectIds);
            }

            // 3. 拼接模糊查询条件
            if (isValid(nursingProject.getName())) {
                projectWrapper.like("name", nursingProject.getName());
            }
            if (isValid(nursingProject.getStatus())) {
                projectWrapper.like("status", nursingProject.getStatus());
            }
            projectWrapper.eq("status", "1");

            // 4. 执行分页查询
            IPage<NursingProject> result = nursingProjectDAO.selectPage(page, projectWrapper);

            List<NursingProject> list = result.getRecords();
            long total = result.getTotal();
            response = new PageResponseBean<>(list);
            response.setTotal(total);
        } catch (Exception e) {
            e.printStackTrace();
            response = new PageResponseBean<>(500, "查询未包含护理项目失败");
        }

        return response;
    }
}
